package component.fy.com.common_module.widget;

import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.view.View;

/**
 * 给RecyclerView的Grid添加空格
 */
public class MyGridItemDecoration extends RecyclerView.ItemDecoration {
    private final int spacing;
    private final int spanCount;
    private final boolean showEdge;
    private final float pre;

    /**
     * @param space    item之间的空间
     * @param count    列数
     * @param showEdge 是否显示左右边缘
     */
    public MyGridItemDecoration(int space, int count, boolean showEdge) {
        this.spacing = space;
        this.spanCount = count;
        this.showEdge = showEdge;
        pre = spacing * 1.0f / spanCount;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view,
                               RecyclerView parent, RecyclerView.State state) {
        int position = parent.getChildAdapterPosition(view);
        if (position == RecyclerView.NO_POSITION) {
            return;
        }
        int column = position % spanCount;
        if (showEdge) {
            outRect.left = (int) (spacing - column * pre);
            outRect.right = (int) ((column + 1) * pre);
        } else {
            outRect.left = (int) (column * pre);
            outRect.right = (int) (spacing - (column + 1) * pre);
        }

        if (position < spanCount) {
            outRect.top = spacing;
        }
        outRect.bottom = spacing;
    }
}
